// 已发布页面

import React, { useState, useEffect } from 'react';
import { Button, Card, Space, Input, DatePicker, Alert } from 'antd';
import { SearchOutlined, ReloadOutlined, StopOutlined } from '@ant-design/icons';
import NewsPublish from '../../../components/publish-manage/NewsPublish';
import usePublish from '../../../hooks/usePublish';
import useSimpleAuth from '../../../hooks/useSimpleAuth';
import { useSelector } from 'react-redux';
import { RootState } from '../../../store';
import './publish.scss';
import type { Dayjs } from 'dayjs';
import { News } from '../../../types';

const { RangePicker } = DatePicker;

const Published: React.FC = () => {
  // 使用简化版权限钩子
  const { isSuperAdmin, isRegionAdmin, filterNewsByDepartment } = useSimpleAuth();
  
  // 从Redux获取当前用户信息
  const currentUser = useSelector((state: RootState) => state.user.userInfo);
  const userRegion = currentUser?.region || '';
  
  // 使用新的usePublish hook
  const { sunsetNews, getPublishedNews } = usePublish();
  
  // 状态管理
  const [dataSource, setDataSource] = useState<News[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<Error | null>(null);
  
  // 搜索状态
  const [searchTitle, setSearchTitle] = useState<string>('');
  const [dateRange, setDateRange] = useState<[Dayjs | null, Dayjs | null] | null>(null);
  
  // 加载数据
  const fetchData = async () => {
    setLoading(true);
    try {
      const data = await getPublishedNews();
      
      // 使用专用的新闻过滤函数过滤新闻
      const filteredData = filterNewsByDepartment(data);
      setDataSource(filteredData);
      setError(null);
    } catch (err) {
      setError(err instanceof Error ? err : new Error('加载数据失败'));
    } finally {
      setLoading(false);
    }
  };
  
  // 组件挂载时加载数据
  useEffect(() => {
    fetchData();
  }, []);
  
  // 过滤数据
  const filteredData = dataSource.filter(item => {
    // 标题过滤
    const titleMatch = !searchTitle || 
      (item.title && item.title.toLowerCase().includes(searchTitle.toLowerCase()));
    
    // 日期过滤
    let dateMatch = true;
    if (dateRange && dateRange[0] && dateRange[1]) {
      const itemDate = item.publishTime ? new Date(item.publishTime) : null;
      const startDate = dateRange[0]?.toDate();
      const endDate = dateRange[1]?.toDate();
      
      if (startDate && endDate && itemDate) {
        // 设置结束日期为当天结束
        endDate.setHours(23, 59, 59, 999);
        dateMatch = itemDate >= startDate && itemDate <= endDate;
      }
    }
    
    return titleMatch && dateMatch;
  });
  
  // 下线新闻
  const handleNewsUnpublish = async (id: string | number) => {
    const success = await sunsetNews(id);
    if (success) {
      fetchData(); // 刷新数据
    }
  };
  
  // 重置搜索条件
  const resetSearch = () => {
    setSearchTitle('');
    setDateRange(null);
  };

  // 根据用户角色显示权限提示信息
  const renderPermissionAlert = () => {
    if (isSuperAdmin()) {
      return (
        <Alert
          message="您是超级管理员，可以查看和管理所有部门的已发布新闻"
          type="info"
          showIcon
          style={{ marginBottom: 16 }}
        />
      );
    }
    
    if (isRegionAdmin()) {
      return (
        <Alert
          message={`您是管理员，只能查看和管理${userRegion}部门的已发布新闻`}
          type="warning"
          showIcon
          style={{ marginBottom: 16 }}
        />
      );
    }
    
    return (
      <Alert
        message="您是编辑，只能查看和管理自己创建的已发布新闻"
        type="warning"
        showIcon
        style={{ marginBottom: 16 }}
      />
    );
  };

  return (
    <div className="publish-container">
      <Card>
        <div className="header">
          <h2>已发布列表</h2>
          <Space>
            <Button 
              icon={<ReloadOutlined />} 
              onClick={fetchData} 
              loading={loading}
            >
              刷新
            </Button>
          </Space>
        </div>
        
        {/* 添加部门隔离提示 */}
        {renderPermissionAlert()}
        
        {/* 搜索区域 */}
        <div className="search-area" style={{ marginBottom: 16 }}>
          <Space wrap>
            <Input
              placeholder="搜索标题"
              value={searchTitle}
              onChange={e => setSearchTitle(e.target.value)}
              prefix={<SearchOutlined />}
              allowClear
              style={{ width: 200 }}
            />
            <RangePicker
              value={dateRange}
              onChange={dates => setDateRange(dates)}
              placeholder={['开始日期', '结束日期']}
            />
            <Button onClick={resetSearch}>重置</Button>
          </Space>
        </div>
        
        {error && (
          <div className="error-message">
            加载失败: {error.message}
          </div>
        )}
        
        <NewsPublish 
          dataSource={filteredData} 
          loading={loading}
          button={(id) => (
            <Button 
              type="primary" 
              danger
              size="small"
              icon={<StopOutlined />} 
              onClick={() => handleNewsUnpublish(id)}
            >
              下线
            </Button>
          )} 
        />
      </Card>
    </div>
  );
};

export default React.memo(Published); 